<?php

namespace app\admin\controller\dormitory;

use app\admin\model\DormitoryDormBed;
use app\admin\model\DormitoryGarden;
use app\admin\model\DormitoryDorm;
use app\admin\model\Student;
use app\common\controller\Backend;
use think\Db;

class Distribute extends Backend
{
    /**
     * @var \app\common\model\Faculty
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['searchList'];
    protected $gardenData = [];
    protected $categoryData = [];
    protected $typeData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Faculty');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $total = $this->model
                ->alias('a')
                ->where($where)
                ->count();

            $list = $this->model
                ->alias('a')
                ->join('__STUDENT__ b', 'b.faculty_id = a.id and b.is_bed = 0', 'left')
                ->where($where)
                ->field('a.id,a.name,COUNT(b.gender = 1 OR NULL) boy_count,COUNT(b.gender = 2 OR NULL) girl_count')
                ->order($sort, $order)
                ->group('a.id')
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {

                $params['creator_id'] = $this->auth->id;
                $params['department_id'] = $this->auth->department_id;

                $result = $this->model->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                $params['creator_id'] = $this->auth->id;
                $params['department_id'] = $this->auth->department_id;

                // 启动事务
                Db::startTrans();
                try{

                    $row->save($params);

                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    $this->error($this->model->getError());
                }

                $this->success();
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 选择寝室分配方式
     *
     * @return string
     */
    public function select()
    {
        $id = $this->request->request('id', 0);
        $gender = $this->request->get('gender', 0);

        if (!$id || !$gender) {
            echo '参数错误';die;
        }

        $faculty = $this->model->find($id);

        $this->view->assign('faculty', $faculty);
        $this->view->assign('gender', $gender);
        $this->view->assign('gender_text', Student::$genderList[$gender]);

        return $this->view->fetch();
    }

    /**
     * 按寝室分配
     *
     * @return string
     */
    public function dorm()
    {
        if ($this->request->isPost()) {

            $garden_number = $this->request->post('garden_number');
            $building_number = $this->request->post('building_number');
            $faculty_id = $this->request->post('faculty_id');
            $gender = $this->request->post('gender');
            $floor = $this->request->post('floor/a');
            $dorm_ids = $this->request->post('dorm/a');

            $student_list = Student::where('faculty_id', $faculty_id)
                ->where('gender', $gender)
                ->where('is_bed', 0)
                ->field('id')
                ->select();

            if ($student_list) {
                $bed_list = DormitoryDormBed::alias('a')
                    ->join('__DORMITORY_DORM__ b', 'b.number = a.dorm_number and a.garden_number = b.garden_number and a.building_number = b.building_number')
                    ->whereIn('a.status', DormitoryDormBed::XIANZHI)
                    ->whereIn('b.id', $dorm_ids)
                    ->where('a.garden_number', $garden_number)
                    ->where('a.building_number', $building_number)
                    ->where('b.status', DormitoryDorm::NORMAL)
                    ->field('a.id,a.dorm_number,a.garden_number,a.building_number')
                    ->limit(0, count($student_list))
                    ->select();

                // 启动事务
                Db::startTrans();
                try{

                    foreach ($student_list as $key => $value) {
                        if (isset($bed_list[$key])) {

                            DormitoryDormBed::where('id', $bed_list[$key]['id'])
                                ->update([
                                    'student_id' => $value['id'],
                                    'status' => DormitoryDormBed::ZAIYONG
                                ]);

                            DormitoryDorm::where('number', $bed_list[$key]['dorm_number'])
                                ->where('garden_number', $bed_list[$key]['garden_number'])
                                ->where('building_number', $bed_list[$key]['building_number'])
                                ->setInc('bed_used_count');

                            Student::where('id', $value['id'])->update(['is_bed' => 1]);

                        }
                    }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage() ? $e->getMessage() : '分配失败');
                }

                $this->success();
            } else {
                $this->error('分配失败, 没有要分配的学生');
            }



        } else {

            $faculty_id = $this->request->request('id', 0);
            $gender = $this->request->get('gender', 0);

            if (!$faculty_id || !$gender) {
                echo '参数错误';die;
            }

            $faculty = $this->model->findOrFail($faculty_id);

            $student_count = Student::where('faculty_id', $faculty_id)
                ->where('gender', $gender)
                ->where('is_bed', 0)
                ->count();

            $garden_list = DormitoryGarden::all();

            $this->view->assign('faculty', $faculty);
            $this->view->assign('gender', $gender);
            $this->view->assign('student_count', $student_count);
            $this->view->assign('gender_text', Student::$genderList[$gender]);
            $this->view->assign('garden_list', $garden_list);

            return $this->view->fetch();
        }

    }

    /**
     * 按床位分配
     *
     * @return string
     */
    public function bed()
    {
        if ($this->request->isPost()) {

            $garden_number = $this->request->post('garden_number');
            $building_number = $this->request->post('building_number');
            $faculty_id = $this->request->post('faculty_id');
            $gender = $this->request->post('gender');
            $floor = $this->request->post('floor/a');
            $dorm_number = $this->request->post('dorm/a');
            $bed_ids = $this->request->post('bed/a');

            $student_list = Student::where('faculty_id', $faculty_id)
                ->where('gender', $gender)
                ->where('is_bed', 0)
                ->field('id')
                ->select();

            if ($student_list) {
                $bed_list = DormitoryDormBed::alias('a')
                    ->whereIn('a.status', DormitoryDormBed::XIANZHI)
                    ->whereIn('a.id', $bed_ids)
                    ->field('a.id,a.dorm_number,a.garden_number,a.building_number')
                    ->limit(0, count($student_list))
                    ->select();

                // 启动事务
                Db::startTrans();
                try{

                    foreach ($student_list as $key => $value) {
                        if (isset($bed_list[$key])) {

                            DormitoryDormBed::where('id', $bed_list[$key]['id'])
                                ->update([
                                    'student_id' => $value['id'],
                                    'status' => DormitoryDormBed::ZAIYONG
                                ]);

                            DormitoryDorm::where('number', $bed_list[$key]['dorm_number'])
                                ->where('garden_number', $bed_list[$key]['garden_number'])
                                ->where('building_number', $bed_list[$key]['building_number'])
                                ->setInc('bed_used_count');

                            Student::where('id', $value['id'])->update(['is_bed' => 1]);

                        }
                    }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('分配失败');
                }

                $this->success();
            } else {
                $this->error('分配失败, 没有要分配的学生');
            }

        } else {
            $faculty_id = $this->request->request('id', 0);
            $gender = $this->request->get('gender', 0);

            if (!$faculty_id || !$gender) {
                echo '参数错误';die;
            }

            $faculty = $this->model->findOrFail($faculty_id);

            $student_count = Student::where('faculty_id', $faculty_id)
                ->where('gender', $gender)
                ->where('is_bed', 0)
                ->count();

            $garden_list = DormitoryGarden::all();

            $this->view->assign('faculty', $faculty);
            $this->view->assign('gender', $gender);
            $this->view->assign('student_count', $student_count);
            $this->view->assign('gender_text', Student::$genderList[$gender]);
            $this->view->assign('garden_list', $garden_list);

            return $this->view->fetch();
        }
    }




}
